package cn.com.dpc;

import java.lang.reflect.Field;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.dpc.bean.User;
import cn.com.dpc.service.AlarmService;
import cn.com.dpc.util.DataService;
import cn.com.dpc.util.HttpGet;
import cn.com.dpc.util.UserTable;

public class MainActivity extends Activity {
	private String ipStr = "218.249.218.105";
	private String userId = "";
	private String password = "";
	// private String ipStr = "61.236.134.146";

	private String result = "";
	private SQLiteDatabase sql = null;

	public AlertDialog registerdialog = null;
	public ProgressDialog m_Dialog = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splashscreen);

		// Display the current version number
		PackageManager pm = getPackageManager();
		try {
			PackageInfo pi = pm.getPackageInfo("cn.com.dpc", 0);
			TextView versionNumber = (TextView) findViewById(R.id.versionNumber);
			versionNumber.setText("Version " + pi.versionName);
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		initUser();
		// initData();

		this.stopService(new Intent(this, AlarmService.class));

	}

	private void initUser() {
		new Thread() {
			public void run() {
				try {
					User user = DataService.queryUser(MainActivity.this);
					if (user != null) {
						ipStr = user.getIp();
						userId = user.getUserId();
						password = user.getPassword();
						m_handlerSuccess.sendEmptyMessage(0);
					} else {
						m_handlerNoUser.sendEmptyMessage(0);
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}.start();
	}

	private Handler m_handlerSuccess = new Handler() {
		public void handleMessage(Message msg) {
			// m_progressDlg.hide();
			try {
				initData();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	private Handler m_handlerNoUser = new Handler() {
		public void handleMessage(Message msg) {
			// m_progressDlg.hide();
			try {
				login();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private void login() {
		AlertDialog.Builder ad = new AlertDialog.Builder(this);
		ad.setTitle("账号登录");
		ad.setView(View.inflate(this, R.layout.login, null));
		registerdialog = ad.create();
		registerdialog.setButton("登录", new OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				EditText passwordEt = (EditText) registerdialog
						.findViewById(R.id.txt_password);
				EditText userEt = (EditText) registerdialog
						.findViewById(R.id.txt_username);
				EditText ipEt = (EditText) registerdialog
						.findViewById(R.id.ipname);

				ipStr = ipEt.getText().toString();
				userId = userEt.getText().toString();
				password = passwordEt.getText().toString();

				try {
					Field field = registerdialog.getClass().getSuperclass()
							.getDeclaredField("mShowing");
					field.setAccessible(true);
					field.set(registerdialog, true);
				} catch (Exception e) {
					e.printStackTrace();
				}

				if (ipStr.equals("") || userId.equals("")
						|| password.equals("")) {
					try {
						Field field = registerdialog.getClass().getSuperclass()
								.getDeclaredField("mShowing");
						field.setAccessible(true);
						field.set(registerdialog, false);
					} catch (Exception e) {
						e.printStackTrace();
					}

					registerdialog.findViewById(R.id.txt_loginerror)
							.setVisibility(View.VISIBLE);
					return;
				}

				// 生成注册对话框
				m_Dialog = ProgressDialog.show(MainActivity.this, "请等待...",
						"正在登录...", true, true);

				new Thread() {
					public void run() {
						try {
							result = HttpGet.getResult("http://" + ipStr
									+ "/andriod!isExsit.do?u=" + userId + "&p="
									+ password, MainActivity.this, "utf8");
							if (result.trim().equals("1")) {
								User user = new User();
								user.setIp(ipStr);
								user.setUserId(userId);
								user.setPassword(password);
								DataService.insertUser(MainActivity.this, user);
								m_handlerLoginSuc.sendEmptyMessage(0);
							} else {
								m_handlerLoginFail.sendEmptyMessage(0);
							}

						} catch (Exception e) {
							e.printStackTrace();
							// m_handlerLoginFail.sendEmptyMessage(0);
						}
					}
				}.start();

			}
		});
		registerdialog.setButton2("关闭", new OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// registerdialog.dismiss();
				MainActivity.this.finish();
			}
		});
		registerdialog.show();
	}

	private Handler m_handlerLoginSuc = new Handler() {
		public void handleMessage(Message msg) {
			// m_progressDlg.hide();
			try {
				m_Dialog.dismiss();
				// 提示登录成功
				Toast.makeText(MainActivity.this, "登录成功，加载用户数据中...",
						Toast.LENGTH_SHORT).show();
				// 转到主题页面
				initData();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private Handler m_handlerLoginFail = new Handler() {
		public void handleMessage(Message msg) {
			// m_progressDlg.hide();
			try {
				m_Dialog.dismiss();
				// 提示登录不成功
				registerdialog.show();
				registerdialog.findViewById(R.id.txt_loginerror).setVisibility(
						View.VISIBLE);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private void initData() {
		new Thread() {
			public void run() {
				try {
					result = HttpGet.getResult("http://" + ipStr
							+ "/andriod!findDistrictAndStation.do?userId="
							+ userId, MainActivity.this, "utf8");
					Log.v("dpc", result);
					DataService.deleteData(MainActivity.this, userId);
					DataService.insertData(MainActivity.this, userId, result);
					m_handler.sendEmptyMessage(0);
				} catch (Exception e) {
					Log.v("dpcError",
							e.getLocalizedMessage() + " " + e.getMessage());
					e.printStackTrace();
				}
			}
		}.start();
	}

	private Handler m_handler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				Log.v("dpc1", "login");
				Intent mainIntent = null;
				mainIntent = new Intent(MainActivity.this,
						MainTabActivity.class);

				// JSONObject jsonObject = new JSONObject(result);
				// JSONArray jsonArray = jsonObject.getJSONArray("root");
				// JSONArray jsonArrayNew = new JSONArray();
				// for (int i = 0; i < jsonArray.length(); i++) {
				// JSONObject jo = jsonArray.getJSONObject(i);
				// int districtType = jo.getInt("districtType");
				// if (districtType == 2) {
				// jsonArrayNew.put(jo);
				// }
				// }
				//
				// Bundle bundle = new Bundle();
				// bundle.putString("districtList", jsonArrayNew.toString());
				// mainIntent.putExtras(bundle);

				MainActivity.this.startActivity(mainIntent);
				MainActivity.this.finish();

			} catch (Exception e) {
				Log.v("dpcError",
						e.getLocalizedMessage() + " " + e.getMessage());
				e.printStackTrace();
			}
		}
	};

}